package com.gree.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import com.gree.entity.TrsT021RunmoveRecord;
import org.springframework.web.multipart.MultipartFile;
import com.gree.service.ITrsT021RunmoveRecordService;

import java.text.SimpleDateFormat;

public class Files {

	public static final String FORMAT_yMd = "yyyy-MM-dd";
	public static final SimpleDateFormat simp = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.SSSS", Locale.CHINA);
	/** 创建文件夹 返回rootFile路径 */
	public static String writeFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
			return path;
		}
		return path;
	}

	/** 文件日志 */
	public static void writeByFileWriter(String path, String fileName,String message) {
		File files = new File(path);
		File file = new File(path+ "/"+fileName.replaceAll(".txt", "__log.log"));
		if (!file.exists()|| !files.exists()) {
			files.mkdirs();
			try {
			
				file.createNewFile();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		BufferedWriter bw = null;
		try {
			FileWriter fw = new FileWriter(file, true);
			bw = new BufferedWriter(fw);
			bw.write("[" + simp.format(new Date()) + "]  " + message
					+ "\r\n\r\n");
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void editorReduction() {
		ITrsT021RunmoveRecordService recordService = (ITrsT021RunmoveRecordService) SpringBeanFactoryUtils
				.getBean("recordService");// 运行记录
		recordService.editorReduction();
	}

	public static String getFileUpload(String COMP_CODE, String loginId,String USER_ID, MultipartFile file) throws Exception {
		String encoding = "UTF-8";
		ITrsT021RunmoveRecordService ckps = (ITrsT021RunmoveRecordService) SpringBeanFactoryUtils.getBean("recordService");// 运行记录
		String infoId = UniqueIDTool.getUniqueID();
		String result = null;
		// 文件目录
		String succpath = getFilePath(COMP_CODE, loginId, infoId);
		try {
			File dir = new File(succpath + "//" + file.getOriginalFilename());

			long dr = (dir.length() / 1024 / 1024);

			if ((getSpace() - dr) < 5) {
				String message = MessageID.LESS_DISK_SPACE.replace("#drive#",
						dir.getParent().substring(0, 2));
				result = StringTool.getJSONObject("error", message);
				writeByFileWriter(succpath, file.getOriginalFilename(), message);
				return result;
			} else {
				String message = MessageID.DOWNLOAD_FILE.replace("#FILE_NAME#",file.getOriginalFilename());
				file.transferTo(dir);
				File fi = new File(succpath + "/" + file.getOriginalFilename());
				
			   if (fi.exists() && fi.length() <= 2339) {
				   writeByFileWriter(fi.getParent(), fi.getName(), message);
					String messag = MessageID.FILE_DOES_NOT.replace("#FILE_NAME#",fi.getName());
					writeByFileWriter(fi.getParent(), fi.getName(), messag);
					TrsT021RunmoveRecord objs = new TrsT021RunmoveRecord();
					objs.setInfoId(infoId);
					objs.setCompanyId(COMP_CODE);// 公司代码
					objs.setFileName(file.getOriginalFilename());// 文件名称
					objs.setHoldUser(USER_ID);// 操作对象
					objs.setLoginId(loginId);
					objs.setLockFlag("N");// 运行状态
					objs.setNumLines(3.0);		
					objs.setMessage(messag); // 更新消息
					objs.setEndTime(new Date());
					objs.setRunTime(new Date());
					objs.setFileUrl(succpath + "/" + file.getOriginalFilename());
					ckps.appendNonEmptyRunRecord(objs);
					result = StringTool.getJSONObject("error", messag);
					return result;
				}else{
				FileInputStream in = new FileInputStream(fi);
				InputStreamReader read = new InputStreamReader(in, encoding);
				BufferedReader buffer = new BufferedReader(read);
				String lineTxt = null;
				Integer sum = 0;
				while ((lineTxt = buffer.readLine()) != null) {
					long starTime = System.currentTimeMillis();
					sum = sum + 1;
					if (lineTxt.equals("")) {
						continue;
					}
					if (sum == 1 && lineTxt.indexOf("SSC_" + COMP_CODE.trim()+ "_JournalSlip_") == -1) {
						writeByFileWriter(fi.getParent(),fi.getName(), message);
						Files.writeByFileWriter(fi.getParent() , fi.getName(),formats(sum, "验证头文件", starTime));
						String messag = MessageID.FILE_EXPORT_ERROR.replace("#FILE_NAME#", fi.getName());
						writeByFileWriter(fi.getParent() ,fi.getName(),messag);
						TrsT021RunmoveRecord obs = new TrsT021RunmoveRecord();
						obs.setInfoId(infoId);
						obs.setFileName(fi.getName());
						obs.setCompanyId(COMP_CODE);
						obs.setHoldUser(USER_ID);
						obs.setLockFlag("X");// 运行状态
						obs.setMessage(messag); // 更新消息
						obs.setLoginId(loginId);
						obs.setFileUrl(succpath + "/" + file.getOriginalFilename());
						obs.setEndTime(new Date());
						obs.setRunTime(new Date());
						
						obs.setNumLines(Double.parseDouble(String.valueOf(sum)));
						obs.setRowLines(Double.parseDouble(String.valueOf(sum)));
						
						ckps.appendNonEmptyRunRecord(obs);
						result = StringTool.getJSONObject("error", messag);
						continue;
					} else if (sum == 1 && lineTxt.indexOf("SSC_" + COMP_CODE.trim()+ "_JournalSlip_") != -1) {
						TrsT021RunmoveRecord record = new TrsT021RunmoveRecord();
						record.setInfoId(infoId);
						record.setCompanyId(COMP_CODE);// 公司代码
						record.setFileName(file.getOriginalFilename());// 文件名称
						record.setHoldUser(USER_ID);// 操作对象
						record.setLoginId(loginId);
						record.setLockFlag("E");// 运行状态
						record.setNumLines(Double.parseDouble(lineTxt.substring(lineTxt.indexOf("d")+1))+2);						
						record.setFileUrl(succpath + "/" + file.getOriginalFilename());
						ckps.appendNonEmptyRunRecord(record);
						result = StringTool.getJSONObject("success", message);
						
						writeByFileWriter(fi.getParent(),fi.getName(), message);
					}
				}
				buffer.close();
				read.close();
				in.close();
				return result;
			}
			}
		} catch (Exception e) {
			ckps.deleteRunmoveRecordById(infoId);
			String message = MessageID.FILE_UPOLAD.replace("#FILE_NAME#",file.getOriginalFilename());
			writeByFileWriter(succpath, file.getOriginalFilename(), message + "\r\n\r\n" + e.getMessage());
			result = StringTool.getJSONObject("error", message);
			return result;
		}
	}
	/** 备份目录，文件上传成功 */
	public static String getFilePath(String COMP_CODE, String loginId,String infoId) {
		SimpleDateFormat simp = new SimpleDateFormat(FORMAT_yMd, Locale.CHINA);
		String dates = simp.format(new Date());
		Properties pro = System.getProperties();
		String drive = pro.getProperty("user.dir").substring(0, 2);
		String path = drive + MessageID.INIT_PATH + dates + "/" + COMP_CODE+ "/" + loginId + "/" + infoId;
		return writeFile(path);
	}

	/**
	 * 删除文件，可以是文件或文件夹
	 * 
	 * @param fileName
	 *            要删除的文件名
	 * @return 删除成功返回true，否则返回false
	 */
	public static boolean delete(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			System.out.println("删除文件失败:" + fileName + "不存在！");
			return false;
		} else {
			if (file.isFile())
				return deleteFile(fileName);
			else
				return deleteDirectory(fileName);
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param fileName
	 *            要删除的文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				System.out.println("删除单个文件" + fileName + "成功！");
				return true;
			} else {
				System.out.println("删除单个文件" + fileName + "失败！");
				return false;
			}
		} else {
			System.out.println("删除单个文件失败：" + fileName + "不存在！");
			return false;
		}
	}

	/**
	 * 删除目录及目录下的文件
	 * 
	 * @param dir
	 *            要删除的目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public static boolean deleteDirectory(String dir) {
		// 如果dir不以文件分隔符结尾，自动添加文件分隔符
		if (!dir.endsWith(File.separator))
			dir = dir + File.separator;
		File dirFile = new File(dir);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
			System.out.println("删除目录失败：" + dir + "不存在！");
			return false;
		}
		boolean flag = true;
		// 删除文件夹中的所有文件包括子目录
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = Files.deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
			// 删除子目录
			else if (files[i].isDirectory()) {
				flag = Files.deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag) {
			System.out.println("删除目录失败！");
			return false;
		}
		// 删除当前目录
		if (dirFile.delete()) {
			System.out.println("删除目录" + dir + "成功！");
			return true;
		} else {
			return false;
		}
	}

	/** 剩余空间大小：M */
	public static Long getSpace() {
		Properties pro = System.getProperties();
		String drive = pro.getProperty("user.dir").substring(0, 2);
		File file = new File(drive);
		long freeSpace = file.getFreeSpace();
		return (freeSpace / 1024 / 1024);
	}

	public static String formats(Integer sum, String message, long starTime) {
		SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS", Locale.CHINA);
		long endTime = System.currentTimeMillis();
		long Time = endTime - starTime;
		String	mess="["+simp.format(new Date())+"]第【" + sum + "】行的【" + message + "】耗时【" + Time+ "】毫秒";
		//System.out.println(mess);
		return mess;
	}
	public static String geSum(Integer sum, long starTime) {
		SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS", Locale.CHINA);
		long endTime = System.currentTimeMillis();
		long Time = endTime - starTime;
		String message="["+simp.format(new Date())+"]第【" + sum + "】行的运行总时长【" + Time + "】毫秒";
		//System.out.println(message);
		return message;
	}

}
